using System;
using System.ComponentModel;
using Microsoft.VisualStudio.Modeling;

namespace DslCrossModelFramework.ModelTraversal {
    public class ModelPathSerializationTypeConverter : TypeConverter {

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
            return ((destinationType == typeof(string)) || base.CanConvertTo(context, destinationType));
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) {
            if(value == null) {
                return string.Empty;
            }
            ModelPath modelPath = value as ModelPath;
            if(modelPath == null) {
                throw new ArgumentException(string.Format("Expected a ModePath instead of a {0}", value.GetType()), "value");
            }

            if (context == null) {
                return modelPath.SerializeToString();
            }
            else {
                return modelPath.ToString();
            }
        }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
            return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType));
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
            if(value is string && string.IsNullOrEmpty(value as string)) {
                return new ModelPath();
            }
            ModelPath modelPath = ModelPath.DeserializeFromString(value as string, new CrossModelManager());
            return modelPath;
        }
    }
}